import { reqOrderAddress, reqOrderInfo, reqBuyNowGoods, reqSubmitOrder, reqPreBuyInfo, reqPayStatus } from '@/api/orderpay'

// 导入 async-validator 对参数进行验证
import Schema from 'async-validator'

import formDate from '@/utils/formDate'
const app = getApp()
Page({
  data: {
    totalAmount: 0,
    address: {},
    list: [],
    buyName: '', // 订购人姓名
    buyPhone: '', // 订购人手机号
    deliveryDate: '选择送达日期', // 期望送达日期
    blessing: '', // 祝福语
    show: false, // 期望送达日期弹框
    minDate: new Date().getTime(),
    currentDate: new Date().getTime()
  },
  onShow() {
    this.getAddress()
    this.getorderInfo()
  },
  onLoad(options) {
    console.log(options)
    this.setData({
      ...options
    })
  },
  onUnload() {
    // 页面销毁重置公共数据
    app.globalData.address = {}
  },

  // 获取订单详情
  async getorderInfo() {
    const { goodsId, blessing } = this.data
    let { data } = goodsId ? await reqBuyNowGoods({ goodsId, blessing }) : await reqOrderInfo()
    const orderItem = data.cartVoList.find(item => item.blessing)
    this.setData({
      address: data,
      blessing: !orderItem ? '' : orderItem.blessing,
      list: data.cartVoList,
      totalAmount: data.totalAmount
    })
  },

  // 获取地址
  async getAddress() {
    // 判断是否从地址列表页选择地址回来
    const address = app.globalData.address
    if (address.id) {
      return this.setData({
        address: address
      })
    }
    const { data } = await reqOrderAddress()
    this.setData({
      address: data
    })
  },
  // 选择期望送达日期
  onShowDateTimerPopUp() {
    this.setData({
      show: true
    })
  },

  // 期望送达日期确定按钮
  onConfirmTimerPicker(event) {
    this.setData({
      show: false,
      deliveryDate: formDate(event.detail)
    })
    console.log(this.data.deliveryDate)
  },

  // 期望送达日期取消按钮 以及 关闭弹框时触发
  onCancelTimePicker() {
    this.setData({
      show: false,
      minDate: new Date().getTime(),
      currentDate: new Date().getTime()
    })
  },

  // 跳转到收货地址
  toAddress() {
    wx.navigateTo({
      url: '/modules/setting-module/pages/address/list/index'
    })
  },

  // 提交订单
  async submitOrder() {
    // 从 data 中结构数据
    const {
      buyName,
      buyPhone,
      deliveryDate,
      blessing,
      list,
      address
    } = this.data

    // 组织请求参数
    const params = {
      buyName,
      buyPhone,
      deliveryDate,
      remarks: blessing,
      cartList: list,
      userAddressId: address.id
    }

    // 对请求参数进项验证
    const { valid } = await this.validatorPerson(params)

    if (!valid) return

    let res = await reqSubmitOrder(params)
    if (res.code === 200) {
      this.orderCode = res.data
      this.advancePay(res.data)
    }
  },
  // 获取预支付信息
  async advancePay(id) {
    try {
      const res = await reqPreBuyInfo(id)
      if (res.code === 200) {
        const payInfo = await wx.requestOrderPayment(res.data)
        // 获取支付结果
        if (payInfo.errMsg === 'requestPayment:ok') {
          // 查询订单的支付状态
          const payStatus = await reqPayStatus(id)

          if (payStatus.code === 200) {
            wx.redirectTo({
              url: '/modules/orderPayModule/pages/order/list/index',
              success: () => {
                wx.toast({
                  title: '支付成功',
                  icon: 'success'
                })
              }
            })
          }
        }
      }
    } catch (error) {
      wx.toast({ title: '支付失败' })
    }
  },
  // 对新增收货地址请求参数进行验证
  validatorPerson(params) {
    // 验证收货人，是否只包含大小写字母、数字和中文字符
    const nameRegExp = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$'

    // 验证手机号，是否符合中国大陆手机号码的格式
    const phoneReg = '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$'

    // 创建验证规则
    const rules = {
      userAddressId: [{ required: true, message: '请选择收货地址' }],
      buyName: [
        { required: true, message: '请输入收货人姓名' },
        { pattern: nameRegExp, message: '收货人姓名不合法' }
      ],
      buyPhone: [
        { required: true, message: '请输入收货人手机号' },
        { pattern: phoneReg, message: '收货人手机号不合法' }
      ],
      deliveryDate: { required: true, message: '请选择送达时间' }
    }

    // 传入验证规则进行实例化
    const validator = new Schema(rules)
    // 调用实例方法对请求参数进行验证
    return new Promise((resolve) => {
      validator.validate(params, (errors) => {
        if (errors) {
          // 如果验证失败，需要给用户进行提示
          wx.toast({ title: errors[0].message })
          // 如果属性值是 false，说明验证失败
          resolve({ valid: false })
        } else {
          // 如果属性值是 true，说明验证成功
          resolve({ valid: true })
        }
      })
    })


  }
})
